package com.itheima.ssm.controller;
//用户contraller

import com.itheima.ssm.domain.Role;
import com.itheima.ssm.domain.UserInfo;
import com.itheima.ssm.service.IuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(path = "/user")
public class UserController {
    @Autowired
    private IuserService iuserService;

    @RequestMapping(path = "/findAll")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userList = iuserService.findAll();
        mv.addObject("userList", userList);
        mv.setViewName("user-list");
        return mv;
    }

    //    用户添加
    @RequestMapping(path = "/save")
    public String save(UserInfo userInfo) throws Exception {
        iuserService.save(userInfo);
        return "redirect:findAll";
    }

    //    查找指定ID的用户
    @RequestMapping(path = "/findById")
    public ModelAndView findById(String id) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = iuserService.findById(id);
        mv.addObject("user", userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    //   查询用户以及可以添加的角色【查询没有的角色】
    @RequestMapping(path = "/findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userId) throws Exception {
        ModelAndView mv = new ModelAndView();
//        根据用户id查询用户
        UserInfo userInfo = iuserService.findById(userId);
//        根据用户id查询可以添加到角色
        List<Role> otherRole = iuserService.findOtherRole(userId);
        mv.addObject("user", userInfo);
        mv.addObject("roleList", otherRole);
        mv.setViewName("user-role-add");
        return mv;
    }

    //    给用用户添加角色，在user_role中添加[表单中携带用户id，以及role list]
    @RequestMapping(path = "/addRoleToUser")
    public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId,
                                @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception {
        iuserService.addRoleToUser(userId, roleIds);
        return "redirect:findAll";
    }
}
